#include "i2c.h"

I2C_HandleTypeDef hi2c1;

void PY_I2C1_Init(void)
{
    hi2c1.Instance             = I2C1;
    hi2c1.Mode                 = HAL_I2C_MODE_MASTER;
    hi2c1.Init.ClockSpeed      = 1000000;
    hi2c1.Init.DutyCycle       = I2C_DUTYCYCLE_2;
    hi2c1.Init.OwnAddress1     = 0x78;
    hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
    hi2c1.Init.NoStretchMode   = I2C_NOSTRETCH_DISABLE;

    if(HAL_I2C_Init(&hi2c1) != HAL_OK) {
        APP_ErrorHandler();
    };
}

void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c)
{
    GPIO_InitTypeDef GPIO_InitStruct = {0};
    if(hi2c1.Instance == I2C1) {
        __HAL_RCC_I2C_CLK_ENABLE();
        __HAL_RCC_GPIOB_CLK_ENABLE();

        /**I2C pin configuration
        PB3     ------> I2C1_SCL
        PB4     ------> I2C1_SDA
        */
        GPIO_InitStruct.Pin = GPIO_PIN_3 | GPIO_PIN_4;
        GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;                     /* open drain */
        GPIO_InitStruct.Pull = GPIO_PULLUP;                         /* pull up */
        GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;          
        GPIO_InitStruct.Alternate = GPIO_AF6_I2C1;                  /* Reuse as I2C */
        HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);                     /* GPIO initialization */

        /*Reset I2C*/
        __HAL_RCC_I2C_FORCE_RESET();
        __HAL_RCC_I2C_RELEASE_RESET();
    }
}

void HAL_I2C_MspDeInit(I2C_HandleTypeDef* i2cHandle)
{
    if(i2cHandle->Instance==I2C1) {
        /* Peripheral clock disable */
        __HAL_RCC_I2C_CLK_DISABLE();

        /**I2C pin configuration
        PB3     ------> I2C1_SCL
        PB4     ------> I2C1_SDA
        */
        HAL_GPIO_DeInit(GPIOB, GPIO_PIN_3);
        HAL_GPIO_DeInit(GPIOB, GPIO_PIN_4);
    }
}
